package com.szh.mysobproject.ui.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.szh.mysobproject.databinding.QaListItemBinding
import com.szh.mysobproject.model.UserQa
import com.szh.mysobproject.util.DateHelper
import com.szh.mysobproject.util.setFixOnClickListener

class QaListAdapter (private val adapterDelegate: AdapterDelegate):
    PagingDataAdapter<UserQa.Content, QaListAdapter.QaListViewHolder>(QaDiffCallback()) {

    inner class QaListViewHolder(val binding: QaListItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    class QaDiffCallback : DiffUtil.ItemCallback<UserQa.Content>() {

        override fun areItemsTheSame(oldItem: UserQa.Content, newItem: UserQa.Content): Boolean {
            return oldItem.wendaComment.id == newItem.wendaComment.id
        }

        override fun areContentsTheSame(oldItem: UserQa.Content, newItem: UserQa.Content): Boolean {
            return oldItem == newItem
        }


    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: QaListViewHolder, position: Int) {
        val item = getItem(position) ?:return
        val itemView = holder.itemView
        val binding = holder.binding
        val tvQaTitle = binding.tvQaTitle
        val tvQaDesc = binding.tvQaDesc
        itemView.setFixOnClickListener {
            adapterDelegate.onItemClick(it,position)
        }
        tvQaTitle.text  = item.wendaTitle
        tvQaDesc.text = DateHelper.getFriendlyTimeSpanByNow("${item.wendaComment.publishTime}:00")
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QaListViewHolder {
        val binding = QaListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return QaListViewHolder(binding)
    }
}